package engines;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GoogleEngine
{
	String contentString = null;
	String currentLink = null;
	String outputfile = null;
	String id = null;

        String summary = "On a dark night filled with even darker magics, an insane cult attempts to give Nightmare Moon a body and life of her own, utterly separate from Princess Luna. But, when the spell is interrupted by Celestia, something unexpected is created. \n Now, a little black alicorn filly named Nyx finds herself living under the care of Twilight Sparkle, only to be haunted by memories and emotions from her past. \n Is she Nightmare Moon reborn or is she simply a doppelganger with a soul and mind of her own? Can Twilight Sparkle protect Nyx from those refuse to see past her dragon eyes and black coat? \n Or, will Nyx be forced to inherit the sins that may not even be hers and become the greatest evil Equestria has ever known?";
        String author = "Pen Stroke";
        String title = "Past Sins";

	boolean deleteOkay = false;

        private Vector<String> chapterContents = new Vector<String>();
        private Vector<String> chapterLink = new Vector<String>();
        private Vector<String> chapterTitle = new Vector<String>();
	private Vector<File> fileDeleter = new Vector<File>();

	public void setLink(String l)
	{
		currentLink = l;
	}

	public void parseForID()
	{
		id = currentLink.replace("https://docs.google.com/document/d/", "");
		id = id.replace("/edit", "");
	}

	public void getChapter()
	{

		try {
			URLConnection con = new URL("https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html").openConnection();
			InputStream in = con.getInputStream();
			Scanner s = new Scanner(in);
			contentString = s.nextLine();
			s.close();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if(contentString.contains("<img"))
                {
			parseForImages();
                }


	}

	private void parseForImages()
	{
		String sub = null;
		int i = 0;

		while(contentString.contains("src=\"https"))
		{
			i = contentString.indexOf("<img",i);
			i = contentString.indexOf("src", i);
			sub = contentString.substring(i + 5 , contentString.indexOf("\"", i+5));
			System.out.println(sub);
			contentString = contentString.replaceFirst(sub.substring(0, sub.indexOf(".com/")+5), "");

			try {
				getImage(sub,sub.substring(sub.indexOf(".com") + 5));
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}


		}
	}

	private void getImage(String url, String out) throws MalformedURLException, IOException
	{
		URLConnection urlCon = new URL(url).openConnection();
		InputStream in = urlCon.getInputStream();

		File image = new File(out);
		fileDeleter.add(image);

		FileOutputStream o = new FileOutputStream(image);

		int i;
		byte[] bite = new byte[2048];

		while((i = in.read(bite,0,2048))!=-1)
		{
			o.write(bite,0,i);
		}

		o.close();
		in.close();
	}


        public void addChapterContents()
        {
            chapterContents.add(contentString);
        }

        public void writeChapters()
        {
            int i = 0;
            while(i<chapterContents.size())
            {

                //System.out.println(this.chapterContents);
                File f = new File(String.valueOf(i) + ".html");
                fileDeleter.add(f);
                try {

                    PrintWriter p = new PrintWriter(new FileOutputStream(f));
                    p.write(chapterContents.elementAt(i));
                    p.close();
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(GoogleEngine.class.getName()).log(Level.SEVERE, null, ex);
                }
                i++;
            }
        }

        public void cleanUp()
	{
		int i = 0;

		while(fileDeleter.size() != 0)
		{
			if(true)
			{
				System.out.println(((File) fileDeleter.get(0)).getName());
				((File) fileDeleter.get(i)).delete();
				fileDeleter.remove(0);
			}

		}
                System.out.println("Done!");
	}

	public void convert()
	{
		String command = "ebook-convert 0.html out.epub";
		try {
			Process p = Runtime.getRuntime().exec(command);
			p.waitFor();
			deleteOkay = true;
			//p.getOutputStream().
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

        public void osCommand(String command)
        {

		try {
			Process p = Runtime.getRuntime().exec(command);
			InputStream in = p.getInputStream();
                        InputStreamReader isr = new InputStreamReader(in);
                        BufferedReader read = new BufferedReader(isr);

                        String r = null;

                        while((r=read.readLine())!=null)
                            System.out.println(r);

		}
                catch (IOException e)
                {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        }

        public String getContentSring()
        {
            return contentString;
        }

        public void populateTOC()
        {
            Scanner s;
            try
            {
                URLConnection con = new URL("https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html").openConnection();
                InputStream in = con.getInputStream();
                s = new Scanner(in);
            }
            catch (IOException ex)
            {
                Logger.getLogger(GoogleEngine.class.getName()).log(Level.SEVERE, null, ex);
            }

            String text;

            while(contentString.contains("href"))
            {
                    text = contentString.substring(contentString.indexOf("href=")+6, contentString.indexOf("\"",contentString.indexOf("href=")+6));
                    contentString= contentString.replaceFirst("href=\"" + text, "");
                    chapterLink.add(text);
            }

        }

        public String getChapterLink(int i)
        {
            return chapterLink.get(i);
        }

        public int chapterLinkCount()
        {
            return chapterLink.size();
        }

        public void test()
        {
            System.out.println(chapterContents);
        }

        public void createIndex() throws FileNotFoundException
        {
            int progress = 0;

            File directoryData = new File("index.opf");
            fileDeleter.add(directoryData);
            PrintWriter out = new PrintWriter(new FileOutputStream(directoryData,true));

            out.println("<?xml version='1.0' encoding='utf-8'?>");
            out.println("<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\" unique-identifier=\"calibre-uuid\">");
            out.println("<metadata xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:opf=\"http://www.idpf.org/2007/opf\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:calibre=\"http://calibre.kovidgoyal.net/2009/metadata\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\">");
            out.println("<dc:description>" + summary + "</dc:description>");
            //out.println("<dc:language>" + dat.language + "</dc:language>");
            out.println("<dc:creator role=\"aut\">" + author + "</dc:creator>");
            //out.println("<opf:meta name=\"calibre:series\" content=\"" + dat.series + "\"/>");
            out.println("<dc:title>" + title + "</dc:title>");
            out.println("</metadata>");

            out.println(" <manifest>");

            while(progress != (chapterContents.size()))
            {
                out.println("  <item href=\"" + progress + ".html\" id=\"html" + progress + "\" media-type=\"application/xhtml+xml\"/>");
                progress++;
            }

            out.println("</manifest>");

            progress = 0;

            out.println("<spine toc=\"ncx\">");

            while(progress != (chapterContents.size() + 1))
            {
                out.println("<itemref idref=\"html" + progress + "\"/>");
                progress++;
            }
            out.println("</spine>");
            out.println("<guide/>");
            out.println("</package>");

            out.close();

        }

        public void addChapterTitle()
        {
            chapterTitle.add(contentString.substring(contentString.indexOf("<title>")+7, contentString.indexOf("</title>")));
        }
}
